package com.area.cth.ws;

import com.alibaba.fastjson.JSONObject;
import com.area.cth.pojo.Message;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/chat/{pid}")
@Component
public class ChatEndpoint {

    private static final Map<Integer, Session> chatUsers = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("pid") Integer pid) {
        chatUsers.put(pid, session);
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println(message);
        Message msg = JSONObject.parseObject(message, Message.class);
        Session session = chatUsers.get(msg.getReceiveUser());
        msg.setCreateTime(LocalDateTime.now());
        if (session != null) {
            try {
                session.getBasicRemote().sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                Db.save(msg);
            }
        } else {
            Db.save(msg);
        }
    }

    @OnClose
    public void onClose(@PathParam("pid") Integer pid) {
        chatUsers.remove(pid);
    }
}